<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <PageTools ref="values" @query="search">
          <template v-slot:before>
            <el-button type="primary" plain @click="addFn">添加分类</el-button>
          </template>
        </PageTools>
        <el-divider />
        <!-- 表格模块 -->
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column prop="image" label="图片" align="center">
            <template v-slot="{ row }">
              <img class="tableImg" :src="row.image" height="70">
            </template>
          </el-table-column>

          <el-table-column prop="title" label="标题" align="center" />

          <el-table-column prop="desc" label="介绍" align="center" />

          <el-table-column prop="address" label="操作" width="180" align="center">
            <template v-slot="{ row }">
              <el-button
                plain
                type="primary"
                size="small"
                @click="editFn(row.id)"
              >编辑</el-button>
              <el-button
                plain
                type="danger"
                size="small"
                @click="delFn(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-divider />
        <!-- 分页 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            background
            layout="prev, pager, next"
            :page-size="limit"
            :total="total"
            @current-change="pageChange"
          />
        </el-row>
      </el-card>
      <!-- 弹窗 -->
      <el-dialog
        :title="form.id ? '编辑分类':'新增分类'"
        :visible.sync="dialogVisible"
        @close="closeFn"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" style="width:80%" />
          </el-form-item>
          <el-form-item label="介绍" prop="desc">
            <el-input v-model="form.desc" type="textarea" rows="5" style="width:80%" />
          </el-form-item>
          <!-- 放置图片
          action：设置图片的接口上传
           :http-request 覆盖默认的上传行为（也就是覆盖action属性的），可以自定义上传的实现
           :file-list上传文件事件
           :limit="1"只能上传一条
           el-upload标签添加`:on-remove`-->
          <el-form-item label="封面">
            <div>
              <el-upload
                label="图片"
                action="#"
                :http-request="uploadFn"
                :file-list="fileList"
                :limit="1"
                list-type="picture-card"
                :on-remove="removeFn"
                :color="colors"
                :class="{ disable: fileList.length > 0 }"
              >
                <!-- 添加属性，控制组件只能上传一张图片 -->
                <!-- 动态添类名，控制上传按钮的显示 -->
                <i class="el-icon-plus" />
              </el-upload>
            </div>
          </el-form-item>

          <!-- 放置图片 -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button plain size="small" @click="closeFn">取 消</el-button>
          <el-button type="primary" plain size="small" @click="confrimFn">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// var COS = require('cos-js-sdk-v5');
import COS from 'cos-js-sdk-v5'
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKID5QgmfMsDNL7kEWcYMyPdhcLsFSTN8jAS',
  SecretKey: 'JRM3czAAxYw99xYwBHG3d1CCzYw75qRp'
})
// 获取分类列表
import {
  GetClassfication,
  addClassfication,
  delClassfication,
  getroles,
  updateClassfication,
  gettotal
} from '@/api/Classfications'
export default {
  data() {
    return {
      fileList: [
        /* {url:'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}  */
      ],
      tableData: [],
      total: 0,
      limit: 5, // 每页长度
      start: 0, // 开始获取的下标
      dialogVisible: false,
      form: {
        title: '',
        desc: '',
        image: ''
      },
      // rules
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入描述', trigger: 'blur' }]
      },
      //
      colors: [
        { color: '#f56c6c', percentage: 20 },
        { color: '#e6a23c', percentage: 40 },
        { color: '#5cb87a', percentage: 60 },
        { color: '#1989fa', percentage: 80 },
        { color: '#6f7ad3', percentage: 100 }
      ]
    }
  },
  created() {
    this.GetClassficationList()
  },
  methods: {
    // 渲染页面
    async GetClassficationList() {
      const res = await GetClassfication({
        _limit: this.limit,
        _start: this.start
      })
      // console.log(144, res);
      this.tableData = res.data
      const a = await gettotal()
      console.log(153, a)
      // a里面的data是数量  总的数量
      this.total = a.data
      // console.log(156,this.total);
    },
    // 点击分页实现
    // 规律，例如每页有4条数据，点到第三页，下标就是从8开始；公式：（点击的页数-1）*每页的数据
    async pageChange(current) {
      this.start = (current - 1) * this.limit
      // console.log(163, this.start, current);
      // 刷新页面
      await this.GetClassficationList()
    },
    // 新增
    addFn() {
      this.dialogVisible = true
    },
    // 头像
    uploadFn(data) {
      // data：就是选择图片后得到的图片对象
      // data.file：这个file属性的值才是真正传递给后端的文件
      // console.log(333);
      // console.log(25, data);
      this.fileList.push({
        url: ''
      })
      cos.putObject(
        {
          Bucket: 'renzi-79-1313460496' /* 必须 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: Date.now().toString() /* 必须 */,
          StorageClass: 'STANDARD',
          Body: data.file, // 上传文件对象
          onProgress: (progressData) => {
            // console.log(JSON.stringify(progressData));
            // console.log(99,progressData);
            // 进度条
            this.percentage = progressData.percent * 100
          }
        },
        (err, data) => {
          // console.log(36, err || data);
          // err值为null表示上传成功，否则不成功
          // err返回的是false，取反就是true
          if (!err) {
            /* this.fileList.push({
                url:'https://' + data.Location

            }) */
            this.fileList[0].url = 'https://' + data.Location
            this.form.image = 'https://' + data.Location
          }
        }
      )
    },
    // bug的时候处理
    removeFn() {
      this.fileList = []
    },
    // 新增确认
    // 不需要id
    async confrimFn() {
      await this.$refs.form.validate()
      if (this.form.id) {
        // 编辑
        await updateClassfication(this.form)
      } else {
        // 新增
        await addClassfication(this.form)
      }
      this.closeFn()
    },
    closeFn() {
      //  补充
      //  清空表单
      this.form = {
        title: '',
        desc: '',
        image: ''
      }
      // 清空校验规则
      this.$refs.form.resetFields()
      // 关闭弹窗
      this.dialogVisible = false
      // 刷新页面
      this.GetClassficationList()
    },
    // 删除操作
    delFn(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(async() => {
          await delClassfication(id)
          // 刷新页面
          await this.GetClassficationList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑操作
    async editFn(id) {
      this.dialogVisible = true
      // 回填
      const res = await getroles(id)
      this.form = res.data
    },
    // 搜索，子传父，声明方法。通过$ref,把内容value传过来。调用查询的接口
    async search() {
      const value = this.$refs.values.value
      // console.log(263,value);
      const ress = await GetClassfication({
        _limit: this.limit,
        title_contains: value
      })
      // res.data里面包含数据
      // console.log(268,ress);
      // 总数
      this.total = ress.data.length
      this.tableData = ress.data
    }
  }
}
</script>

<style lang='scss' scoped>
::v-deep.disable {
  .el-upload--picture-card {
    display: none;
  }
}
.tableImg{
  width: 150px;
  height: 120px;
  //图片写死宽高的情况，控制拉伸效果的样式
  object-fit: contain;
  //object-fit: cover;
}
</style>
